<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button icon="el-icon-plus" size="small" type="primary" @click="handleRole">新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="this.$store.state.logoing" :data="list">
              <el-table-column label="序号" width="100" type="index" :index="handleIndex" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="handleAuth(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="toPrimary(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delList(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination layout="sizes, prev, pager, next, ->,total" :total="total" :current-page="fillterParams.page" :page-size="fillterParams.pagesize" :page-sizes="[1, 2, 3, 4, 5]" @size-change="sizeChangennn" @current-change="changePage" />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 弹窗结构 -->
    <el-dialog :title="title" :visible.sync="isShowAddBox" @close="noBtnCancel">
      <el-form ref="roleForm" v-loading="dialogLoading" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="isShowAddBox = false">取消</el-button>
        <el-button type="primary" @click="btnCancel">确认</el-button>
      </template>
    </el-dialog>
    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible.sync="showAuthDialog">
      <div v-loading="$store.state.logoing">
        <el-tree ref="myTree" :check-strictly="true" :data="permissionData" show-checkbox node-key="id" :default-expand-all="true" :props="defaultProps" />
      </div>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showAuthDialog=false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { reqGetRoleListAPI, reqDeleteRoleAPI, reqAddRoleAPI, reqGetRoleDetailAPI, reqUpdateRoleAPI, reqAssignPermAPI } from '@/api/setting'
import { reqGetPermissionList } from '@/api/permission'
import { translateListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data () {
    return {
      defaultCheckedKeys: [], // 默认权限数据
      permissionData: [], // 存储权限数据
      roleId: '',
      showAuthDialog: false, // 分配权限弹窗
      isShowAddBox: false, // 弹出参数
      dialogLoading: false, // 弹窗加载参数
      // 查询参数
      fillterParams: {
        page: 1,
        pagesize: 5
      },
      // 角色列表
      list: [],
      // 角色列表的总数
      total: 0,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      },
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  computed: {
    title () {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created () {
    this.reqGetRoleList()
  },
  methods: {
    // 获取角色信息
    async reqGetRoleList () {
      try {
        const { data } = await reqGetRoleListAPI(this.fillterParams)
        this.list = data.rows
        this.total = data.total
      } catch {
        this.$message.error('获取角色信息失败')
      }
    },
    // 页面跳转处理
    changePage (page) {
      this.fillterParams.page = page
      this.reqGetRoleList()
    },
    // 每页多少条
    sizeChangennn (pagesize) {
      this.fillterParams.pagesize = pagesize
      // console.log(this.fillterParams.pagesize)
      this.reqGetRoleList()
    },
    // 表格序号运算
    handleIndex (index) {
      const { page, pagesize } = this.fillterParams
      return (page - 1) * pagesize + index + 1
    },
    // 删除角色
    async delList (id) {
      try {
        const ret = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (ret === 'cancel') return
        const delRet = await reqDeleteRoleAPI(id)
        this.$message.success(delRet.message)
        this.reqGetRoleList()
      } catch (err) {
        this.$message.error('未知的网络错误')
      }
    },
    // 弹窗部分
    handleRole () {
      this.isShowAddBox = true
    },
    // 添加角色
    btnCancel () {
      this.$refs.roleForm.validate(async (valid) => {
        if (!valid) return
        if (!this.form.id) {
          try {
            const ret = await reqAddRoleAPI(this.form)
            this.$message.success(ret.message)
            this.isShowAddBox = false
          } catch {
            this.$message.error('未知的网络错误,请稍后在试')
          }
        } else {
          try {
            const ret = await reqUpdateRoleAPI(this.form)
            this.$message.success(ret.message)
            this.isShowAddBox = false
          } catch {
            this.$message.error('未知的网络错误,请稍后在试')
          }
        }
      })
    },
    // 取消按钮
    noBtnCancel () {
      this.reqGetRoleList()
      this.$refs.roleForm.resetFields()
      this.form = this.$options.data().form
    },
    // 编辑角色过去信息
    async toPrimary (id) {
      this.dialogLoading = true
      this.handleRole()
      try {
        const ret = await reqGetRoleDetailAPI(id)
        this.form = ret.data
      } catch (err) {
        this.message.error('获取信息异常')
      }
      this.dialogLoading = false
    },
    // 分配角色弹窗
    handleAuth (id) {
      this.showAuthDialog = true
      this.roleId = id
      this.loadAuthList(id)
    },
    // \获取权限列表数据
    async loadAuthList (id) {
      // 加载角色的权限数据
      // try {
      const ret = await reqGetPermissionList()
      const retn = await reqGetRoleDetailAPI(id)
      Promise.all([ret, retn]).then((rets) => {
        if (rets[0].code === 10000 && rets[1].code === 10000) {
          this.permissionData = translateListToTreeData(rets[0].data, '0')
          this.$refs.myTree.setCheckedKeys(rets[1].data.permIds)
        } else {
          this.$message.error(rets.message)
        }
      }).catch(() => {
        this.$message.error('失败了')
      })
    },
    // 确定提交更改权限
    async handleSubmit () {
      try {
        const ret = await reqAssignPermAPI({
          id: this.roleId,
          permIds: this.$refs.myTree.getCheckedKeys()
        })
        if (ret.code === 10000) {
          this.showAuthDialog = false
          return this.$message.success('分配权限成功')
        }
        return this.$message.error(ret.message)
      } catch (err) {
        console.log(err)
        this.$message.error('出错了')
      }
    }
  }
}
</script>
